package service;

import Dao.ClientDao;
import domain.Client;
import utils.PasswordGenerator;
import utils.jdbcUtilByDruid;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ClientsService {
    private ClientDao clientsDao = new ClientDao();

    //列出所有的客户信息
    public List<Client> listAllClients() throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        return clientsDao.queryMulti("select * from Clients ", Client.class);
    }

    //根据客户的id进行删除操作
    public boolean deleteClient(int id) throws SQLException, IOException, ClassNotFoundException {
        int i = clientsDao.update("delete from Clients where ClientId = ?", id);
        return i > 0;
    }

    //根据id查询对应的客户信息
    public Client queryClientsById(int id) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        return clientsDao.querySingle("select * from Clients where ClientId = ? ", Client.class, id);
    }

    // 根据用户名查询对应的客户信息
    public Client queryClientsByName(String name) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        return clientsDao.querySingle("select * from Clients where Username = ? ", Client.class, name);
    }

    //用户注册时，需要调用这个方法把数据更新到用户表里面
    //更新的信息：客户ID(自增唯一，不用给定)、用户级别（金牌客户、银牌客户、铜牌客户）、用户注册时间（now()）、客户累计消费总金额(0)；
    //用户名、密码，用户手机号、用户邮箱需要手动输入
    public boolean addClient(String username, String passwordC, String phoneNumber, String email)
            throws SQLException, IOException, ClassNotFoundException {
        int i = clientsDao.update("INSERT INTO Clients (PasswordC, Username, UserLevel, RegistrationDate, " +
                "TotalConsumption, PhoneNumber, Email,State) VALUES (md5(?),?, '铜牌客户', now(), 0, ?, ?,0)",
                passwordC, username, phoneNumber, email);
        if (i > 0) {
            return true;
        }
        return false;
    }

    // 与结账功能有关——根据客户的ClientID对消费总金额进行修改,是个累加的过程先要取出原本的消费总金额
    public void updateTotalConsumption(Double money, Integer ClientID) throws SQLException, IOException,
            ClassNotFoundException {
        BigDecimal bd = (BigDecimal) clientsDao.queryScalar("select TotalConsumption from clients  " +
                "where ClientId = ?", ClientID);
        money += bd.doubleValue();
        int i = clientsDao.update("update clients set TotalConsumption=? where ClientId = ?", money, ClientID);

    }

    //根据用户的ID得到邮箱号
    public String getEmail(int ClientID) throws SQLException, IOException, ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        return (String) clientsDao.queryScalar("select Email from clients where ClientID=?", ClientID);
    }

    //根据用户的ID修改密码,把这个随机密码记录下来返回给调用这个函数的内部，然后给SendMail.sendMail()把这个消息给用户接收
    public String updatePassword(Integer ClientID) throws SQLException, IOException, ClassNotFoundException {
        String newRandomPassword = PasswordGenerator.generateRandomPassword(9);//生成九位随机密码
        int i = clientsDao.update("update clients set passwordC=md5(?) where ClientID=?",
                newRandomPassword, ClientID);
        return newRandomPassword;
    }

    //用户修改自身密码
    public void updateMyPassword(String newPassword, Integer ClientID) throws SQLException, IOException,
            ClassNotFoundException {
        int i = clientsDao.update("update clients set passwordC=md5(?) where ClientID=?",
                newPassword, ClientID);
        return;
    }

    //忘记密码功能——根据输入的用户名判断存在与否，返回对象
    public Client judgeExist(String username) throws SQLException, IOException, NoSuchFieldException,
            ClassNotFoundException, InstantiationException, IllegalAccessException {
        Client client = clientsDao.querySingle("select * from Clients where Username = ?",
                Client.class, username);
        return client;
    }
    //根据输入的客户ID，密码判断当前是否存在用户
    public boolean judge(Integer ClientID, String password) throws SQLException, IOException,
            NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        Client client = clientsDao.querySingle("select * from Clients where ClientID = ? and passwordC=md5(?)",
                Client.class, ClientID,password);
        if(client == null){
            return false;
        }
        return true;
    }

    //更新state的值，保证密码连续输入错误5次就锁定账户得以实现
    public int updateState(Integer ClientID) {
        Connection connection = null;
        int state0=0;
        try {
            //获取连接，开启事务
            connection = jdbcUtilByDruid.getConnection();
            connection.setAutoCommit(false);//手动提交
            state0 = (Integer) clientsDao.queryScalar("select state from clients where ClientID=? ", ClientID) + 1;
            int i = clientsDao.update("update clients set state=? where ClientID=?", state0, ClientID);
            //没有异常就提交
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();//若出现异常，回滚事务
            } catch (SQLException throwables) {
                throw new RuntimeException(throwables);
            }
        }
        return state0;
    }
    //把状态重置为0
    public void updateState0(Integer ClientID) throws SQLException, IOException, ClassNotFoundException {
        int i=clientsDao.update("update clients set state=0 where ClientID=?",ClientID);
        return;
    }

}
